Lesson 12: Printer Friendly

Use Object-Oriented Programming Techniques

Printing This Lesson

Select what you’d like to include when you print, and then click the Print Lesson button:

Saving This Lesson

For instructions on saving this lesson (shown below), please select the browser you're using.

chrome icon
Chrome
Firefox icon
Firefox
Internet Explorer 10 icon
IE
Safari icon
Safari

Chapter 1

Introduction

Congratulations, you've made it to the last lesson! We've covered a lot of ground since the start of this course. The Food Store application is complete and provides you with a template for creating your own Web store application.

To finish the course, let's discuss an advanced PHP topic—object-oriented programming (OOP). OOP is a hot topic these days, and knowing the basics of it can take your programming career to the next level.

First, we'll discuss what OOP is and what it can do for you in your Web application programming. Next, you'll learn how to incorporate OOP in PHP code and see how to create and use your own OOP classes.

Finally, we'll take a look at an advanced PHP library for interacting with the MySQL server using OOP techniques.

By the end of today, you should have a good foundation in OOP and be ready to incorporate it in your new Web applications. Let's go on to Chapter 2 and get started.

Chapter 2

Object-Oriented Programming Basics

Before you can start working on OOP coding, you need to know how OOP works. OOP uses a completely different paradigm than how you've been coding so far. This requires that you think differently about how your programs work and how you code them.

So far, you've been writing our PHP code using the procedural style of programming. In the procedural style of programming, you create variables and functions within your PHP code to perform certain procedures, such as retrieve data records from the MySQL database and display them on a Web page. The data that you use and the functions you create are completely separate entities with no specific relation to each other.

In OOP, everything is related to a class. A class defines the characteristics of an object that you're using in your application. Every application revolves around handling objects. Our Food Store application revolves around handling three objects: products, customers, and orders.

OOP classes define the objects that your application uses. Each class contains both the data and functions required to interact with the object. Once you define the objects, all your application code needs to do is use the data and functions defined for the objects to process and manipulate them.

The benefit to OOP is that once you create a class for an object, you can use that same object anytime in any other application, because you already have the code handy for using that object. You just plug in the class definition code, and you can use it in your application.

An OOP class is comprised of members. There are two types of members. Class properties define attributes for the object (such as the description, price, and quantity in stock of a product). A class can contain many different property members with each property describing a different feature of the object.

The other type of class member is methods. A class method is similar to the standard PHP functions that you've already been using. Just like a function, the method performs an operation using the properties you define in the class. You create class methods to perform specific functions on the class data, such as a method to buy a product (where you subtract a value from the quantity property) or change the price of the product (where you add or subtract a value to the price property). Each class should be self-contained. The methods in a class should only operate on properties within the class and shouldn't deal with properties in other classes.

Creating a Class in PHP

If your head is spinning right now, don't worry. Hopefully we can clear this up by looking at some code. The first thing you need to do in OOP is create a class. You do that by using a class definition. The class definition declares all the members that comprise the class, both properties and methods. Here's an example of a simple class definition in PHP:

class Product {
public $description;
public $price;
public $quantity;
public $onsale;

public function buyProduct($amount) {
$this->quantity -= $amount;
}
}

This class defines four property members and one method member. Each member is defined using one of three visibility classifications. The visibility of a member determines where you can use or reference that member. There are three visibility keywords used in PHP:

  • Public: The member can be accessed from outside of the class code.
  • Private: The member can only be accessed from inside the class code.
  • Protected: The member can only be accessed from a child class (we'll talk about that a little later).

The Product class example declares all of the members as public, so you can reference them anywhere in your PHP code.

The buyProduct() method uses an odd variable name in the function, $this->quantity. The $this variable is a special identifier that references the current class object. In this example, it points to the $quantity property of the class. Notice the removal of the dollar sign from the quantity variable when referencing it this way. This helps PHP know that you're referencing the $quantity variable from within the class.

Now, let's take a look at how to create an actual object using the Product class.

WarningWarning: Between PHP versions 4.x and 5.x PHP vastly changed the way to define and use classes. The use of the code in this lesson follows the PHP version 5 standards. If you're using a PHP version 4.x server, please consult the PHP online manual for how to create and use classes. You can find the URL for that section of the manual in the Supplemental Material section of this lesson.

Creating Objects

Your PHP code uses the class definition to define objects. Instantiating is the process of creating an object using a class definition. Once you instantiate a class into an object, you can use the object within your application code to reference properties and methods. To instantiate an object in PHP code, you use the following format:

$prod1 = new Product();

This creates the object called $prod1 using the Product class. Once you instantiate an object, you can access the public members of that class from anywhere in your application:


$prod1->description = "carrot";
$prod1->price = 1.50;
$prod1->quantity = 10;

This code sets values for the properties of this object. Notice that you must use the -> symbol to reference the property of the object. The $prod1 variable now contains these values for the properties, and you can use them anywhere within your application code to reference these values. The same applies when you need to use a public method of an object:

$prod1->buyProduct(4);

This calls the buyProduct() method, passing the value 4. Since the buyProduct() method alters the $quantity value in the object, the next time you reference $prod1->quantity, it'll have the value 6.

Writing OOP Code in PHP

Let's write an example program using the Products class so we can see OOP in action. Just follow these steps:

  1. Create a folder called oop in the WampServer www folder.
  2. Create a file called example1.php in the oop folder.
  3. Open the file in a text editor, and add the following code:
  4. <?php
    class Product {
       public $description;
       public $price;
       public $quantity;

    public function printProduct() { echo "Product: $this->description<br>\n"; printf("Price: $%.2f<br>\n", $this->price); echo "Quantity: $this->quantity<br>\n"; }

    public function buyProduct($amount) { $this->quantity -= $amount; }

    }

    $prod1 = new Product(); $prod1->description = "Carrots"; $prod1->price = 1.50; $prod1->quantity = 10; echo "Just added product:<br>\n"; $prod1->printProduct();

    echo "<br>Buying 4 carrots.\n"; $prod1->buyProduct(4); echo "Quantity is now: $prod1->quantity<br>\n"; ?>

  5. Save the file, and exit the text editor.
  6. Open your browser, and go to the URL http://localhost/oop/example1.php. When you view the example1.php Web page, you should see the following output:

    The output of the example1.php program

    The output of the example1.php program

This example defines the Product class, which contains the four properties we discussed, plus two class methods: the buyProduct() method you've already seen and the printProduct() method. The printProduct() method is a quick way to print the property values of the Product object. You can use this method anytime you need to display the object values in your application.

That covers the bare basics of OOP. Now you can say you've written and used an OOP program! Let's move on to Chapter 3 and look at some more features of OOP.

Chapter 3

Expanding on OOP

The simple OOP example we created isn't necessarily the best way to create a class and use it. In that example, you created all of the properties using the public classification. This means that any application that uses the Product class can directly access the properties and modify them with whatever values it wants. That could be dangerous, and it's somewhat frowned upon in OOP circles. What if a wayward application set the price property of a product to a negative value? OOP allows you to be able to code your classes to help prevent accidents like that from happening.

The preferred way to handle properties in a class is to make them private so any external code can't change them. It then creates public methods that allow programs to set and get the property values. You can control exactly what happens to the properties in those public methods. Let's create another example that demonstrates this technique:

  1. Create a file called example2.php in the oop folder.
  2. Open the file in a text editor, and add the following code:
  3. <?php

    class Product { private $description; private $price; private $quantity;

    public function setDescription($value) { $this->description = $value; } public function getDescription() { return $this->description; }

    public function setPrice($value) { if ($value > 0) $this->price = $value; else $this->price = 0; } public function getPrice() { return $this->price; }

    public function setQuantity($amount) { $this->quantity = $amount; } public function getQuantity() { return $this->quantity; }

    public function printProduct() { echo "Product: $this->description<br>\n"; printf("Price: $%.2f<br>\n", $this->price); echo "Quantity: $this->quantity<br>\n"; }

    public function buyProduct($val) { $this->quantity -= $val; } }

    $prod1 = new Product(); $prod1->setDescription("Carrot"); $prod1->setPrice(1.50); $prod1->setQuantity(10);

    echo "Just added product:<br>\n"; $prod1->printProduct();

    echo "<br>Buying 4 carrots.\n"; $prod1->buyProduct(4); echo "Quantity is now: " . $prod1->getQuantity() . "<br>\n";

    ?>

  4. Save the file, and exit the text editor.
  5. Open a browser and go to the URL: http://localhost/oop/example2.php. You should see the following output in your browser window:

    Results of the example2.php code

    Results of the example2.php code

Notice that the new methods set the property values inside the class. Only they're allowed to access the properties directly. If you try using the code:

$prod1->quantity = 10;

in your application, you'll get an error message, since the properties are now private. This provides a basic level of protection for your data. You can put any type of checks in the methods that set property values. The setPrice() method demonstrates this feature by checking the value that the program code assigns to the price property.

There's one downside to protecting your class properties, though. Now it's somewhat of a pain to create a new class object, because you have to use the individual set methods to define each property value. Fortunately, PHP provides an easy way to solve this problem.

Class Constructors

Most OOP languages provide a special method called a constructor. The constructor allows you to automatically define property values when you instantiate an object. PHP uses the special method __construct() to define the constructor:

public function __construct($name, $value, $amount) {
$this->description = $name;
if ($value > 0)
$this->price = $value;
else
$this->price = 0;
$this->quantity = $amount;
}

The constructor for our Product class uses three parameters to assign values to the three class properties when you instantiate an object. Now, to create a new Product object, you must use this format:

$prod1 = new Product("Carrot", 1.50, 10);

You can now use a constructor to force the program code to set the class properties when it instantiates the object. If you choose, you can also block any properties from changing by not providing methods that change the values. That's a lot of control over your code!

Let's play with this concept a little. Follow these steps to build both a class file and an application file:

  1. Create the file Product.inc.php in the oop folder.
  2. Open the file in a text editor, and add the following code:
  3. <?php

    class Product { private $description; private $price; private $quantity;

    public function __construct($name, $value, $amount) { $this->description = $name; if ($value > 0) $this->price = $value; else $this->price = 0; $this->quantity = $amount; }

    public function setDescription($value) { $this->description = $value; } public function getDescription() { return $this->description; }

    public function setPrice($value) { if ($value > 0) $this->price = $value; else $this->price = 0; } public function getPrice() { return $this->price; }

    public function setQuantity($amount) { $this->quantity = $amount; } public function getQuantity() { return $this->quantity; }

    public function printProduct() { echo "Product: $this->description<br>\n"; printf("Price: $%.2f<br>\n", $this->price); echo "Quantity: $this->quantity<br>\n"; }

    public function buyProduct($amount) { $this->quantity -= $amount; }

    public function addProduct($amount) { $this->quantity += $amount; } } ?>

  4. Save that file, and exit the text editor.
  5. Now create another file called example3.php in the oop folder.
  6. Open that file in a text editor, and enter the following code:
  7. <?php

    include("Product.inc.php");

    $prod1 = new Product("Carrots", 1.50, 10); echo "Just added product:<br>\n"; $prod1->printProduct();

    $prod2 = new Product("Onions", 2.00, 15); echo "<br>Just added product:<br>\n"; $prod2->printProduct();

    echo "<br>Buying 4 carrots.\n"; $prod1->buyProduct(4); $quant = $prod1->getQuantity(); echo "Quantity is now: $quant<br>\n";

    echo "Buying 3 onions.\n"; $prod2->buyProduct(3); $quant = $prod2->getQuantity(); echo "Quantity is now: $quant<br>\n";

    echo "Adding 10 more carrots.\n"; $prod1->addProduct(10); $quant = $prod1->getQuantity(); echo "Quantity is now: $quant<br>\n"; ?>

  8. Save the file, and exit the text editor.
  9. Open a browser and go to the URL: http://localhost/oop/example3.php. Your output should look similar to this:

    Output of the example3.php code

    Output of the example3.php code

    The Product.inc.php file contains the class definition code for the Product class. Putting the class definition code in a separate file is a common practice that allows you to use the class in any PHP program you want. Naming the file the same as the class name isn't necessary, but it sure makes life easier! All you have to do is use the include() function to bring the class definition code into your application code. Once you include the class definition, you can use it to create as many class objects as you need to handle your data.

    In the next chapter, you'll see how to extend OOP classes and use that technique to get fancy with accessing the MySQL server.

Chapter 4

Extending Classes

No, I'm not talking about trying to make your course longer! OOP provides a way to extend an existing class by adding additional functionality. That's the whole beauty of OOP. You can take classes and use them as-is, or you can modify just the pieces you need to fit a situation.

Defining a new class that's an extension of another class is called inheritance. The new class (called the child) inherits all of the members of the original class (called the parent). You can then add new members to the child class and even overwrite members of the parent class. If you use the overwritten members, the child members take precedence over the parent members.

To create a class extension, you use the class definition format, along with the extends keyword and the name of the class you're extending:

class Soda extends Product {
.
}

The new class, Soda, automatically contains all of the class members of the Product class. Thus, you can assign values to the $quantity property using the setQuantity() method in Soda, just as you did with the Product class. You can also create new class members to add to the extended class in the class definition. Let's create another example and try this:

  1. Create a file called example4.php in the oop folder.
  2. Open the file in a text editor, and add the following code:
  3. <?php
    include("Product.inc.php");

    class Soda extends Product { private $ounces;

    public function __construct($name, $value, $amount, $size) { parent::setDescription($name); parent::setPrice($value); parent::setQuantity($amount); $this->ounces = $size; }

    public function printProduct() { parent::printProduct(); printf("Size: %.2f ounces<br>\n", $this->ounces); } }

    $prod1 = new Soda("Root Beer", 1.25, 10, 18);

    echo "new product added:<br>\n"; $prod1->printProduct();

    echo "<br>Buying 5 bottles.\n"; $prod1->buyProduct(5); echo "now there's " . $prod1->getQuantity() . " left<br>\n"; $prod1->printProduct(); ?>

  4. Save the file, and exit the text editor.
  5. Open a browser and go to the URL: http://localhost/oop/example4.php.

    When you view the Web page in your browser, it should look like this:

    The output of the example4.php file

    The output of the example4.php file

Because the Soda class extends the Product class, you must use the include() function to include the Product class definition code before you can write the class extension code. The class Soda extends the Product class by adding a new property ($ounces). Also, it overwrites two existing method members of the Product class: the constructor and the printProduct() method.

Both the constructor and printProduct() methods use another odd feature of OOP. The double colon symbol (its official name is the scope resolution operator) allows access to the parent properties and methods from the child class. In this example, I use the get series of methods from the Product class to assign values to the properties contained in the parent. To reference the properties in the parent, you must specifically point to the parent methods using the scope resolution operator:

parent::setDescription($name);

You use the same technique to print the parent properties using the printProduct() method. The only thing the child printProduct() method must add is print the $ounces property.

Using OOP With Your Database

As you've seen throughout this course, the PHP MySQL extension provides lots of functions for interacting with a MySQL server. However, all of these functions use the procedural style of programming. If you're using OOP to create your application, you won't want to mix OOP code with procedural code just to connect with your database.

To resolve this problem, PHP includes another extension package, the MySQL Improved extension (called php_mysqli). The php_mysqli extension provides both OOP classes and procedural functions for connecting to the database, submitting queries, and retrieving result sets. The great thing is that you can use the php_mysqli extension as a parent class and create your own customized methods for submitting queries and retrieving your data. This is where the real power of OOP comes into play!

NoteNote: To use the php_mysqli extension, you must have it installed and activated on your AMP server. The WampServer already has this extension installed and activated. If you're following along on another server, follow the procedure for activating an extension on your server.

The MySQL Improved extension uses the PHP class called mysqli. The basic format for connecting to a MySQL database, submitting a query, and retrieving the result set using the mysqli class is:

$con = new mysqli("localhost", "test", "test", "store");
$query = "SELECT description, price, quantity FROM products";
$result = $con->query($query);
while( $row = $result->fetch_assoc())
{
   $description = $row['description'];
   $price = $row['price'];
   $quantity = $row['quantity'];
}

The process is similar to the mysql_ functions we've used in this course but with an OOP twist.

Combining It All Together

Now let's really take a dive into the OOP world. For the last example, you'll extend the mysqli class to create your own database methods that are specialized to your application environment. First, you need to create your new class, called ProductDatabase:

  1. Create a file called ProductDatabase.inc.php in the oop folder.
  2. Open the file with a text editor, and add the following code:
  3. Print code

    <?php
    include("Product.inc.php");

    class ProductDatabase extends mysqli {

    public function clean_and_query($query) { if (get_magic_quotes_gpc()) $query = stripslashes($query); $query = $this->real_escape_string($query); return $this->query($query); }

    public function getProduct($result) { if ($row = $result->fetch_assoc()) { $prod = new Product($row['description'], $row['price'], $row['quantity']); return $prod; } else { return FALSE; } } } ?>

  4. Save the file, and exit the text editor.

By default, your ProductDatabase class inherits all of the standard methods and properties of the mysqli class, so we'll be able to use the query() and fetch_assoc() methods as normal. This class creates a new method, called clean_and_query(). The purpose of this specialized class is to remove any added slashes by the magic_quotes_gpc feature, and then it uses the mysqli version of the mysql_real_escape_string() function to add any slashes to trouble characters.

The getProducts() method is even trickier. It receives the result of a mysqli query, then processes it in a mysqli fetch_assoc() method. The trick is it puts the returned result in a Product class object for you. This lets you use the methods you created in the Product class to process your product data. Awesome!

Now you can create an application that uses your new class. Follow these steps:

  1. Create a file called example5.php in the oop folder.
  2. Open the file in a text editor, and add the following code:
  3. <?php

    include("ProductDatabase.inc.php");

    $con = new ProductDatabase("localhost", "test", "test", "store"); $query = "SELECT description, price, quantity FROM products"; $result = $con->clean_and_query($query);

    while ( $product = $con->getProduct($result)) { $product->printProduct(); echo "----------------------<br>\n"; } ?>

  4. Save the file, and exit the text editor.
  5. Open a browser and go to the URL: http://localhost/oop/example5.php

    You should see the output of all the records in your products table.

    The output of the example5.php file

    The output of the example5.php file

To use your new class, you must instantiate a new object using the ProductDatabase() constructor. Since it inherits the mysqli class, you can use the same constructor format. Then, use your new clean_and_query() function to submit your database query, and send the results to your new getProducts() method. Then the code uses the printProduct() method to easily display the product information.

It's a great way to build your code library with classes that you can use over and over again. Now, let's go on to Chapter 5 and wrap up this lesson.

Chapter 5

Summary

The PHP language is a great way to test the object-oriented programming waters without having to learn a whole new language. You can leverage your existing PHP programming skills and build applications using OOP principles.

Today you learned how to create a basic OOP class using PHP and then use that class to create objects in an application. The class can contain any number of property and method members. You can define each member to be private only for the class or for public use outside of the class code.

You also discovered how to extend an existing class into a new class using the extends keyword. This enables you to build onto existing classes that you or other programmers have created.

Finally, you found out how to use the extension feature to extend a standard PHP library class, the mysqli class. The mysqli class provides standard methods for submitting queries to a MySQL server and retrieving the result set. You built a sample class that extends the mysqli class to add your own features.

Final Steps

Now that you've finished the last lesson, is there anything else to do? Yes, several things!

  • Quiz, assignment, and FAQs: You still have a quiz for this lesson, as well as an assignment, so be sure to do these. Also, check out the FAQs for this lesson—you might find the answer to something you're wondering about here.
  • Resources for further learning: If you haven't already checked out the Recommended Books and Resources, now would be a great time. When it comes to a topic like Intermediate PHP and MySQL, there's always more to learn. To access these, just click the Resources link.
  • Final exam: Here's the moment all those quizzes have been preparing you for—the cumulative final for this course. Let me give you a tip: Print the final before taking it so you can study and relieve any test anxiety you might have. (You can have the classroom open when you take the final too.) You only get one chance at the final, so you'll want to do your best. To access it, click the Completion link and then click Final Exam. Good luck!
  • Course evaluation: I'd love to know what you thought of this course and if you have any suggestions for improvement. So please take some time, either before or after you take the final, to fill out a brief evaluation. I appreciate your feedback, and future students will too! You'll find the link to this by clicking Completion, and then clicking Evaluation.
  • Discussion Area: The Discussion Area will be open for two more weeks after Lesson 12's release, so please feel free to stop by and ask any questions (except about the final exam) and share your thoughts.

Other Courses

If you enjoyed this course, here are a few other online courses you might be interested in:

Introduction to Database Development
The key to any successful dynamic Web application is the database. It's crucial that you know how to lay out your data requirements in the database before you even start your Web page coding. This course provides the fundamentals for database design and guides you through organizing your data into database objects.

Introduction to SQL
SQL is the language understood by the database server. Knowing how to write proper SQL queries can make the difference between creating a blazing-fast Web site and a ridiculously slow Web site. This course guides you through the basic structure of relational databases, how to read and write simple SQL statements, and advanced data manipulation techniques—all of which are crucial elements to a successful dynamic Web page.

Designing Effective Web Sites
Creating a dynamic Web site isn't all about the PHP code. There are plenty of other elements involved in creating a successful Web site. This course will help you become familiar with good user interface design techniques that will allow your visitors to navigate your site with ease.

Supplementary Material

http://www.php.net/manual/en/language.oop5.php
http://www.php.net/manual/en/language.oop.php

FAQs

Q: If the class definition contains a constructor, can it also contain a destructor?

A: Yes. You can use the __destruct() method to execute statements when a class object is destroyed. You can do this either explicitly or at the end of the PHP script.


Q: Is there a central location where I can find OOP classes for PHP?

A: Yes! The www.phpclasses.org Web site provides a repository where programmers can share their custom PHP classes. You can use lots of cool classes for creating PHP objects in your programs.

Assignment


You've seen how to use OOP to create a special class for processing products from your database. Now let's use that knowledge to work on customers. Create a new class called Customers that lets you build a customer object. Create properties for each of the data fields in the customers table. Create the constructor for the class, allowing you to create a new customer object. Create methods so you can change a customer's e-mail address and home address. The home address should allow you to change the address, city, state, and ZIP code in one method.

When you've completed this, write an application that uses the Customer class to read the customer table (you can use either the mysql or the mysqli functions) and puts the information into a customer object.